#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMouseEvent>
#include <QAction>
#include <QPushButton>
#include <QApplication>
#include <QDir>
#include <QDebug>
#include <QFileInfo>
#include <QFileDialog>
#include <QGraphicsDropShadowEffect>
#include <QSettings>
#include <QScrollBar>

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint);

    initPlayer();
    initMenu();
    initTrayIcon();
    initicon();
    loadsettings();

    ui->widgetMusicList->setItemBorder(Qt::NoPen);
    ui->widgetMusicList->setBackgroundColor(QColor("#393f3f"));
    ui->widgetMusicList->setItemColor(QColor("#393f3f"));
    ui->widgetMusicList->setTextColor(QColor("#ffffff"));
    ui->widgetMusicList->setSubTextColor(QColor("#aaaaaa"));
    ui->widgetMusicList->setItemHoverColor(QColor("#393f3f"));
    ui->widgetMusicList->setItemSelectedColor(QColor("#393f3f"));
    connect(ui->widgetMusicList, SIGNAL(itemClicked(int)), this, SLOT(slot_musicListClicked(int)));
    this->setFixedHeight(140);
    ui->widgetList->setVisible(false);
}

MainWindow::~MainWindow()
{
    delete ui;
#ifdef USE_FFMPEG
    delete m_ffmpeg;
    m_ffmpeg = NULL;
#endif
}

void MainWindow::sltQuit()
{
    if (m_player->state() == QMediaPlayer::PlayingState) {
        m_player->stop();
    }
    qApp->quit();
}

void MainWindow::initicon()
{
    int nFontId = QFontDatabase::addApplicationFont(":/res/fonts/iconfont.ttf");
    QStringList strlistFontName = QFontDatabase::applicationFontFamilies(nFontId);

    if (strlistFontName.count() > 0)
    {
        m_iconfont = QFont(strlistFontName.at(0));
        m_iconfont.setStyleStrategy(QFont::PreferAntialias);
    }
    else {
        qDebug() << "load iconfont error";
    }

    setIcon(ui->btnMenu, QChar(0xe603), 18);
    setIcon(ui->btnDir, QChar(0xe603), 18);
}

void MainWindow::setIcon( QPushButton *btn, QChar iconCode, uint dwSize /*= 26*/)
{
    if (NULL == btn)
        return;

    m_iconfont.setPixelSize(dwSize);
    btn->setFont(m_iconfont);
    btn->setText(iconCode);
}

void MainWindow::initPlayer()
{
    m_player = new QMediaPlayer(this);

    m_playlist = new QMediaPlaylist(this);
    m_player->setPlaylist(m_playlist);

#ifdef USE_FFMPEG
    m_ffmpeg = new QFFmpegObject(this);
#endif

    connect(m_player, SIGNAL(durationChanged(qint64)), this, SLOT(slot_durationChanged(qint64)));
    connect(m_player, SIGNAL(positionChanged(qint64)), this, SLOT(slot_positionChanged(qint64)));
    connect(m_playlist, SIGNAL(currentIndexChanged(int)), this, SLOT(slot_currentMediaIndexChanged(int)));
}

void MainWindow::scanMusics(const QString &musicPath)
{
    QDir dir(musicPath);
    QFileInfoList filelists = dir.entryInfoList(QDir::Files | QDir::NoDot);
    m_musics.clear();
    ui->widgetMusicList->clear();
    int index = 0;
    foreach(QFileInfo file, filelists) {
        if (file.suffix() == "mp3" || file.suffix() == "MP3") {
            m_playlist->addMedia(QUrl(file.absoluteFilePath()));
            m_musics.append(file.absoluteFilePath());
#ifdef USE_FFMPEG
            QString title;
            QString artist;
            QImage image = m_ffmpeg->getAritstPic(file.absoluteFilePath(), title, artist);
            if (image.isNull()) image.load(":/res/images/ic_music.png");

            ui->labelPixmap->setPixmap(QPixmap::fromImage(image).scaled(ui->labelPixmap->size()));
#endif
            ui->widgetMusicList->addItem(new QtListWidgetItem(index,
                                                              QString("%1.%2").arg(index, 2, 10, QChar('0')).arg(title),
                                                              artist, QPixmap::fromImage(image).scaled(32,32)));
            index++;
        }
    }

    if (!m_musics.isEmpty())
    {
        m_player->play();
    }
}

void MainWindow::showHidePlayList()
{
    bool bOk = ui->widgetList->isVisible();
    bOk = !bOk;
    this->setFixedHeight(bOk ? 325 : 140);
    ui->widgetList->setVisible(bOk);
}

void MainWindow::loadsettings()
{
    QSettings settings(qApp->applicationDirPath() + "/config.ini", QSettings::IniFormat);
    settings.beginGroup("Config");
    m_strMusicPath = settings.value("Path", "Musics").toString();
    settings.endGroup();
    scanMusics(m_strMusicPath);
}

QString MainWindow::changeTime(qint64 secs)
{
    return QString("%1:%2").arg(secs / 60, 2, 10, QChar('0'))
            .arg(secs % 60, 2, 10, QChar('0'));
}

void MainWindow::mousePressEvent(QMouseEvent *e)
{
    if (Qt::LeftButton == e->button())
    {
        m_isPressed = true;
        m_startPos = e->pos();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
    if (m_isPressed) {
        this->move(e->globalPos() - m_startPos);
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *)
{
    m_isPressed = false;
}

void MainWindow::slot_durationChanged(qint64 duration)
{
    ui->progressSlider->setMaximum(duration);
    ui->labelDuration->setText(changeTime(duration / 1000));
}

void MainWindow::slot_positionChanged(qint64 position)
{
    ui->progressSlider->setValue(position < 3000 ? 3000 : position);
    ui->labelPosition->setText(changeTime(position / 1000));
    ui->lrcWidget->postionChanged(position);
}

void MainWindow::slot_currentMediaIndexChanged(int index)
{
    if (index > m_musics.size() || index < 0) return;

    QString strSong = m_musics.at(index);
    QString title;
    QString artist;
#ifdef USE_FFMPEG
    QImage image = m_ffmpeg->getAritstPic(strSong, title, artist);
    if (image.isNull()) image.load(":/res/images/ic_music_128.png");
    ui->labelPixmap->setPixmap(QPixmap::fromImage(image).scaled(ui->labelPixmap->size()));
#else
    QFileInfo fileinfo(strSong);
    QString temp = fileinfo.fileName().remove(".mp3");
    QStringList titles = temp.split("-");
    if (titles.size() == 2) {
        title = temp;
        artist = titles.at(1);
    }
#endif
    ui->widgetTitle->setText(title);
    ui->labelSinger->setText(artist);

    // 加载歌词
    QString strLrc = strSong.remove(strSong.lastIndexOf(".") + 1, 3);
    strLrc.append("lrc");
    ui->lrcWidget->loadLrcFile(strLrc);
}

void MainWindow::sltMenuTriggerd(QAction *action)
{
    int index = action->property("index").toInt();
    switch (index) {
    case 0:
    {
        break;
    }
    case 1:
    {
        m_playlist->previous();
        break;
    }
    case 2:
    {
        if (m_player->state() == QMediaPlayer::PlayingState) {
            m_player->pause();
        } else {
            m_player->play();
        }
        break;
    }
    case 3:
    {
        m_playlist->next();
        break;
    }
    case 4:
    {
        showHidePlayList();
        break;
    }
    case 5:
    {
        hide();
        break;
    }
    case 6:
    {
        sltQuit();
        break;
    }
    default:
        break;
    }
}

void MainWindow::sltPlaymodeTriggerd(QAction *action)
{
    int index = action->property("playmode").toInt();
    m_playlist->setPlaybackMode((QMediaPlaylist::PlaybackMode)index);
}

void MainWindow::initMenu()
{
    int index = 0;
    m_menu = new QMenu(this);
    m_menu->addAction("设    置")->setProperty("index", index++);
    m_menu->addAction("上 一 首")->setProperty("index", index++);
    m_menu->addAction("播放/暂停")->setProperty("index", index++);
    m_menu->addAction("下 一 首")->setProperty("index", index++);

    QMenu *playMode = m_menu->addMenu("播放模式");
    QStringList strModes = QStringList() << "单曲播放" << "单曲循环" << "顺序播放" << "循环播放" << "随机播放";
    QActionGroup *actionGroup = new QActionGroup(this);
    connect(actionGroup, SIGNAL(triggered(QAction *)), this, SLOT(sltPlaymodeTriggerd(QAction *)));
    for (int i = 0; i < strModes.size(); i++) {
        QAction *action = new QAction(strModes.at(i));
        action->setProperty("playmode", i);
        action->setCheckable(true);
        action->setChecked(i == m_playlist->playbackMode());
        playMode->addAction(action);
        actionGroup->addAction(action);
    }

    m_menu->addAction("播放列表")->setProperty("index", index++);
    m_menu->addSeparator();
    m_menu->addAction("托盘运行")->setProperty("index", index++);
    m_menu->addAction("退    出")->setProperty("index", index++);
    ui->btnMenu->setMenu(m_menu);
    connect(m_menu, SIGNAL(triggered(QAction*)), this, SLOT(sltMenuTriggerd(QAction *)));
}

void MainWindow::initTrayIcon()
{
    m_sysTrayicon = new QSystemTrayIcon(this);
    m_sysTrayicon->setContextMenu(m_menu);
    m_sysTrayicon->setIcon(QIcon(":/res/images/ic_music.png"));
    connect(m_sysTrayicon , SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(onActivated(QSystemTrayIcon::ActivationReason)));
    m_sysTrayicon->show();
}


// 激活系统托盘
void MainWindow::onActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch(reason)
    {
    // 单击托盘显示窗口
    case QSystemTrayIcon::Trigger:
    {
        showNormal();
        raise();
        activateWindow();
        break;
    }
    // 双击
    case QSystemTrayIcon::DoubleClick:
    {
        // ...
        break;
    }
    default:
        break;
    }
}

void MainWindow::on_btnDir_clicked()
{
    QString strDir = QFileDialog::getExistingDirectory(this, "选择音乐路径", "./Musics");
    if (strDir.isEmpty()) return;

    QSettings settings(qApp->applicationDirPath() + "/config.ini", QSettings::IniFormat);
    settings.beginGroup("Config");
    settings.setValue("Path", strDir);
    settings.endGroup();
    m_strMusicPath = strDir;
    scanMusics(strDir);
}

void MainWindow::slot_musicListClicked(int index)
{
    if (m_playlist->currentIndex() == index) return;
    m_playlist->setCurrentIndex(index);
}
